package com.itic.appbase.applications.sys.region.controller;

import com.itic.appbase.applications.sys.code.persistence.model.CodeDetail;
import com.itic.appbase.applications.sys.code.vo.CodeDetailVo;
import com.itic.appbase.applications.sys.common.service.InnerCommonService;
import com.itic.appbase.applications.sys.region.persistence.model.Region;
import com.itic.appbase.applications.sys.region.persistence.model.RegionExample;
import com.itic.appbase.applications.sys.region.persistence.model.RegionExample.Criteria;
import com.itic.appbase.applications.sys.region.persistence.model.RegionStat;
import com.itic.appbase.applications.sys.region.persistence.vo.RegionVo;
import com.itic.appbase.applications.sys.region.service.RegionService;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.InitConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/sys/region")
public class RegionController
        extends BaseController {

    @Autowired
    private RegionService                   regionService;

    @Autowired
    private InnerCommonService              innerCommonService;

    public static final Map<String, String> map         = new HashMap<String, String>();
    static {
        map.put("type", "T_DM_REGION_TYPE");
    }

    private static final String             REGION_TYPE = "T_DM_REGION_TYPE";

    @RequestMapping(value = "/init")
    public String init() {
        return "sys/region/regionMain";
    }

    /**
     * 添加页面
     * 
     * @return
     */
    @RequestMapping(value = "/initAdd")
    public String initAdd(@ModelAttribute("pId") String pId, Model model) {
        if (StringHelper.isNotBlank(pId)) {
            Region r = regionService.get(pId);
            if (null != r) {
                model.addAttribute("parentName", r.getName());
                model.addAttribute("thisLevel", String.valueOf(Integer.valueOf(r.getType()) + 1));
            } else {
                model.addAttribute("parentName", InitConst.ROOT_PARENTNAME);
                model.addAttribute("thisLevel", String.valueOf(Integer.valueOf(InitConst.TYPE) + 1));
            }

        }
        return "sys/region/regionAdd";
    }

    /**
     * 查看页面
     * 
     * @return
     */
    @RequestMapping(value = "/initView")
    public String initView(Model model, String id) {
        if (StringHelper.isNotBlank(id)) {
            Region r = regionService.get(id);
            if (null != r) {
                RegionVo regionVo = new RegionVo();
                if (StringHelper.isNotBlank(r.getType())) {
                    r = (Region) innerCommonService.getNameByCode(r, map);
                }
                ValueHelper.model2vo(r, regionVo);
                if (null != r.getpId() && !InitConst.P_ID.equals(r.getpId())) {
                    Region pr = regionService.get(r.getpId());
                    regionVo.setParentName(pr.getName());
                }
                String result = iticJsonMapper.toJson(regionVo);
                model.addAttribute("r", result);
            }
        }
        return "sys/region/regionView";
    }

    /**
     * 统计信息页面
     * 
     * @return
     */
    @RequestMapping(value = "/initStat")
    public String initStat() {
        return "sys/region/regionStat";
    }

    /**
     * 添加
     * 
     * @param region
     * @param dataList
     * @return
     * @throws Throwable
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Map<String, Object> add(Region region) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = ResponseCode.SERVER_ERROR.getCode();
        if (null != region && StringHelper.isNotBlank(region.getName())) {
            result = regionService.add(region);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }

    /**
     * 编辑页面
     * 
     * @return
     */
    @RequestMapping(value = "/initEdit")
    public String initEdit(String id, Model model) {
        if (StringHelper.isNotBlank(id)) {
            Region r = regionService.get(id);
            if (null != r) {
                RegionVo regionVo = new RegionVo();
                ValueHelper.model2vo(r, regionVo);
                if (null != r.getpId() && !InitConst.P_ID.equals(r.getpId())) {
                    Region pRegion = regionService.get(r.getpId());
                    regionVo.setParentName(pRegion.getName());
                }
                String result = iticJsonMapper.toJson(regionVo);
                model.addAttribute("r", result);
            }
        }
        return "sys/region/regionEdit";
    }

    /**
     * 编辑
     * 
     * @param region
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public Map<String, Object> edit(Region region) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = ResponseCode.SERVER_ERROR.getCode();
        if (StringHelper.isNotBlank(region.getId())) {
            result = regionService.edit(region);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }

    /**
     * 级联删除
     * 
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Map<String, Object> delete(String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = ResponseCode.SERVER_ERROR.getCode();
        if (StringHelper.isNotBlank(id)) {
            result = regionService.deleteTree(id);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }

    /**
     * 查找某节点下的行政区划树 没有id默认全查
     * 
     * @param region
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public List<Region> getRegionTree(Region region) {
        if (StringHelper.isBlank(region.getpId())) {
            region.setpId(InitConst.P_ID);
        }
        region.setIsEffective(DBConst.TRUE);
        return regionService.regionTree(region);
    }

    /**
     * 按类别统计信息
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/stat")
    @ResponseBody
    public Map<String, Object> stat() {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<RegionStat> regionStats = regionService.statByType();
        List<RegionStat> resultList = new ArrayList<RegionStat>();
        CodeDetailVo codeDetailVo = new CodeDetailVo();
        codeDetailVo.setType(REGION_TYPE);
        List<CodeDetail> codes = innerCommonService.getCodeDetail(codeDetailVo);
        for (CodeDetail codeDetail : codes) {
            for (RegionStat regionStat : regionStats) {
                if (codeDetail.getCode().equals(regionStat.getType())) {
                    regionStat.setName(codeDetail.getName());
                    resultList.add(regionStat);
                }
            }
        }
        dataMap.put(IticConst.DATA, resultList);
        dataMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
        return dataMap;
    }

    /**
     * 检查代码属性是否重复
     * 
     * @param region
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/isExist")
    @ResponseBody
    public Map<String, Object> isExist(Region region) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        String result = ResponseCode.SERVER_ERROR.getCode();
        if (null != region && StringHelper.isNotBlank(region.getCode())) {
            RegionExample example = new RegionExample();
            Criteria c = example.createCriteria();
            c.andCodeEqualTo(region.getCode()).andIsEffectiveEqualTo(DBConst.TRUE);
            if (StringHelper.isNotBlank(region.getId())) {
                c.andIdNotEqualTo(region.getId());
            }
            List<Region> regions = regionService.list(example);
            result = regions != null && !regions.isEmpty() ? ResponseCode.EXIST.getCode() : ResponseCode.SUCCESS
                    .getCode();
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }
        dataMap.put(IticConst.RESULT, result);
        return dataMap;
    }
}